<?php
/**
 * @Author: lianlianzan(13040@qq.com)
 * @Date:   2019-01-16 16:40:16
 * @Last Modified by:   lianlianzan
 * @Last Modified time: 2021-05-30 20:11:01
 */

use think\Route;
use app\common\builder\Builder;
use app\admin\model\Modules as ModulesModel;
use app\admin\model\Plugins as PluginsModel;

error_reporting(E_ERROR | E_WARNING | E_PARSE);

/**
 * 获取构建器实例
 * @param  string $type 类型（list|form）
 * @return [type] [description]
 * @date   2018-02-02
 * @author 心云间、凝听 <981248356@qq.com>
 */
function builder($type='')
{
    $builder = Builder::run($type);
    return $builder;
}

/**
 * 获取逻辑层实例
 * @param  string $name [description]
 * @return [type] [description]
 * @date   2018-02-02
 * @author 心云间、凝听 <981248356@qq.com>
 */
function logic($name='')
{
    return model($name,'logic');
}

/**
 * 获取服务层实例
 * @param  string $name [description]
 * @return [type] [description]
 * @date   2018-02-02
 * @author 心云间、凝听 <981248356@qq.com>
 */
function getService($name='')
{
    return model($name,'service');
}

/**
 * 检测是否安装某个模块
 * @param  string $name 模块标识
 * @return [type] [description]
 * @date   2017-09-17
 * @author 心云间、凝听 <981248356@qq.com>
 */
function check_install_module($name='')
{
    return ModulesModel::checkInstall($name);
}

/**
 * 检测是否安装某个插件
 * @param  string $name 插件标识
 * @return [type] [description]
 * @date   2017-11-14
 * @author 心云间、凝听 <981248356@qq.com>
 */
function check_install_plugin($name='')
{
    return PluginsModel::checkInstall($name);
}

/**
 * 处理插件钩子
 * @param  [type] $hook 钩子
 * @param  array $params 参数
 * @param  boolean $is_return 是否返回（true:返回值，false:直接输入）
 * @return [type] [description]
 * @date   2018-01-17
 * @author 心云间、凝听 <981248356@qq.com>
 */
function hook($hook, $params = [],$is_return =false)
{
    if ($is_return==true) {
        return \think\Hook::listen($hook, $params);exit;
    }
    \think\Hook::listen($hook, $params);
}

/**
 * 返回某个插件类的类名
 * @param  [type] $name 插件标识
 * @return [type] [description]
 * @date   2017-09-15
 * @author 心云间、凝听 <981248356@qq.com>
 */
function get_plugin_class($name) {
    $class = "\\plugins\\" . $name . "\\Index";
    return $class;
}

/**
 * 获取插件类的配置文件数组
 * @param string $name 插件名
 */
function get_plugin_config($name)
{
    if ($name!='') {
        $class = get_plugin_class($name);
        if (class_exists($class)) {
            $plugin = new $class();
            return $plugin->getConfig();
        } else {
            return [];
        }
    }

}

if (!function_exists('plugin_url')) {
    /**
     * 获取插件地址
     * @param  [type] $url   格式三段式，如：插件标识/控制器名称/操作名
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    function plugin_url($url, $param=[])
    {
        $params = [];
        // 拆分URL
        $url  = explode('/', $url);
        if (isset($url[0])) {
            $params['_plugin'] = $url[0];
        }
        if (isset($url[1])) {
            $params['_controller'] = $url[1];
        }
        if (isset($url[2])) {
            $params['_action'] = $url[2];
        }

        // 合并参数
        $params = array_merge($params, $param);

        return url("home/plugin/execute", $params);

    }
}

/**
 *  url地址转换
 * @param  [type] $url [description]
 * @param  array $param [description]
 * @param  string $type 类型。0完整url，1模块地址，2插件地址，3主题
 * @return [type] [description]
 * @date   2017-11-14
 * @author 心云间、凝听 <981248356@qq.com>
 */
function eacoo_url($url, $param=[],$type=1)
{
    if ($type==2) {//插件
        $url_params = [];
        $query      = parse_url($url);
        $url        = $query['path'];
        if (!empty($query['query'])) {
            parse_str($query['query'],$url_params);
            $url_params = array_merge($url_params, $param);
        }
        if (strtolower($url)!='admin/plugins/config') {
            return plugin_url($url,$url_params);
        } else{
            return url($url,$url_params);
        }
    } else{
        if($url=='' || !$url || strpos($url, 'http://')!==false || strpos($url, 'https://')!==false){
            return $url;
        }
        return url($url,$param);
    }
}

/**
 * 设置日志记录
 * @param  string $content 日志内容
 * @param  string $scene_name 场景类型名
 * @param  string $type 内容类型：如：info,error,debug
 * @date   2017-11-06
 * @author 心云间、凝听 <981248356@qq.com>
 */
function setAppLog($content='', $scene_name='default', $type='info')
{
    if (is_array($content)) {
        $content = var_export($content,true);
    }
    $now = date('Y-m-d H:i:s');
    $remote  = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '0.0.0.0';
    $method  = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'CLI';
    $uri     = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $base_message = "---------------------------------------------------------------\r\n[{$now}] {$remote} {$method} {$uri}\r\n";
    $file = RUNTIME_PATH."applog".DS.$scene_name.DS.$type.'_'.date('Ymd',time()).".log";
    $path = dirname($file);
    !is_dir($path) && mkdir($path, 0755, true);
    $content = $content." \r\n";
    file_put_contents($file,$base_message.$content,FILE_APPEND);
    return true;
}

//设置page的样式
// function setPageConfig($Page) {
// 	$Page->setConfig('prev', '上一页');
// 	$Page->setConfig('next', '下一页');
// 	return $Page;
// }
function sp_password($pw){
	$mi = md5($pw);
	return $mi;
}
//修改过滤函数 20160705
function pwEscape($str) {
    //$str = addslashes($str);
    $str = str_replace(array("\0","%00","\r"), '', $str); //modified@2010-7-5
    $str = preg_replace(array('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','/&(?!(#[0-9]+|[a-z]+);)/is'), array('', '&amp;'), $str);
    $str = str_replace(array("%3C",'<'), '&lt;', $str);
    $str = str_replace(array("%3E",'>'), '&gt;', $str);
    $str = str_replace(array('"',"'","\t",'  '), array('&quot;','&#39;','    ','&nbsp;&nbsp;'), $str); //为什么这里要把两个空格的转换掉
    //$str = str_replace(array('"', "'"), array('&quot;', '&#39;'), $str);

    //$str = str_replace(array('..',')','<','='), array('&#46;&#46;','&#41;','&#60;','&#61;'), $str); //这句话是pw里面checkVar全局过滤的
    //print_r($str);
    return $str;
}
//ueditor编辑器字符转换
function ueditorContent($str) {
    //$str = addslashes($str);
    $str = str_replace(array("&lt;","&gt;"), array('<','>'), $str);
    $str = str_replace(array("&quot;", "&nbsp;", "&amp;"), array('"', '', '&'), $str);
    $str = str_replace(array('\"'), array('"'), $str);
    //print_r($str);exit;
    return $str;
}

//用户cookie加密
function _authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
	$ckey_length = 4;

	$key = md5($key ? $key : C_KEY);
	$keya = md5(substr($key, 0, 16));
	$keyb = md5(substr($key, 16, 16));
	$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

	$cryptkey = $keya.md5($keya.$keyc);
	$key_length = strlen($cryptkey);

	$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
	$string_length = strlen($string);

	$result = '';
	$box = range(0, 255);

	$rndkey = array();
	for($i = 0; $i <= 255; $i++) {
		$rndkey[$i] = ord($cryptkey[$i % $key_length]);
	}

	for($j = $i = 0; $i < 256; $i++) {
		$j = ($j + $box[$i] + $rndkey[$i]) % 256;
		$tmp = $box[$i];
		$box[$i] = $box[$j];
		$box[$j] = $tmp;
	}

	for($a = $j = $i = 0; $i < $string_length; $i++) {
		$a = ($a + 1) % 256;
		$j = ($j + $box[$a]) % 256;
		$tmp = $box[$a];
		$box[$a] = $box[$j];
		$box[$j] = $tmp;
		$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
	}

	if($operation == 'DECODE') {
		if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
			return substr($result, 26);
		} else {
				return '';
			}
	} else {
		return $keyc.str_replace('=', '', base64_encode($result));
	}
}

//是否开启
function isOpenRadioHtmlB($name, $value, $isYesOption=0) {
	if ($value == 1) {
		$check_Y = 'checked';
		$check_N = '';
	} else {
		$check_Y = '';
		$check_N = 'checked';
	}
	$result = '';
	if ($isYesOption) {
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="0" '.$check_N.'> 否</label>';
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="1" '.$check_Y.'> 是</label>';
	} else {
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="0" '.$check_N.'> 关闭</label>';
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="1" '.$check_Y.'> 开启</label>';
	}
	$result .= '';
	return $result;
}
function isOpenRadioValueB($value) {
	$result = $value == 1 ? '<span style="color:red">是</span>' : '否';
	return $result;
}
//选项框 - Bootstrap 2015.08.04
function optionRadioHtmlB($options, $name, $data, $configName = '', $configValue = '', $hasNoSel = 0, $noSelName = '') {
	$result = '<div>';
	if ($hasNoSel) {
		$checked = 0 == $configValue ? 'checked' : '';
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="0" '.$checked.'> '.$noSelName.'</label>';
	}
	if ($options == NULL) {
		$options = array();
	}
	//print_r($options);exit;
	foreach ($options as $key => $value) {
		//print_r($value);exit;
		if ($configValue) {
			$v = $value[$configValue];
		} else {
			$v = $key;
		}
		$checked = $data == $v ? 'checked' : '';
		if ($configName) {
			$n = $value[$configName];
		} else {
			$n = $value;
		}
		$result .= '<label class="radio-inline"><input type="radio" name="'.$name.'" value="'.$v.'" '.$checked.'> '.$n.'</label>';
	}
	$result .= '</div>';
	return $result;
}
//select框(主要针对配置文件里面key和value)
function selectHtmlB($options, $name, $data, $configName = '', $configValue = '', $className = '') {
	$result = '<select id="'.$name.'" name="'.$name.'" class="form-control '.$className.'">';
	$result .= '<option value="0">请选择</option>';
	//print_r($options);exit;
	foreach ($options as $key => $value) {
		if ($configValue) {
			$v = $value[$configValue];
			$selected = $data == $v ? 'selected' : '';
		} else {
			$v = $key;
			$selected = $data == $v ? 'selected' : '';
		}
		if ($configName) {
			$n = $value[$configName];
		} else {
			$n = $value;
		}
		$result .= '<option value="'.$v.'" '.$selected.'>'.$n.'</option>';
	}
	$result .= '</select>';
	return $result;
}

function arrayOut($target){
	$result = array();
	foreach ($target as $value) {
			$result[] = json_decode($value,true);
	}
	return $result;
}
/**
 * 获取随机字符串
 *
 * @param int $length 所需字节数
 * @return string
 */
function randstr($length) {
	return substr(md5(num_rand($length)), mt_rand(0, 32 - $length), $length);
}
/**
 * 获取随机数
 *
 * @param int $length 长度
 * @return string
 */
function num_rand($length) {
	mt_srand((double) microtime() * 1000000);
	$randVal = mt_rand(1, 9);
	for ($i = 1; $i < $length; $i++) {
		$randVal .= mt_rand(0, 9);
	}
	return $randVal;
}

function getAutoTime($timestamp) {
	$current = time();
	$decrease = $current - $timestamp;
	if ($decrease < 0) return time2str($timestamp);
	if ($decrease < 60) return $decrease . '秒前';
	if ($decrease < 3600) return ceil($decrease / 60) . '分钟前';
	$decrease = str2time(time2str($current, 'Y-m-d')) - str2time(time2str($timestamp, 'Y-m-d'));
	if ($decrease == 0) return time2str($timestamp, 'H:i');
	if ($decrease == 86400) return '昨天' . time2str($timestamp, 'H:i');
	if ($decrease == 172800) return '前天' . time2str($timestamp, 'H:i');
	if (time2str($timestamp, 'Y') == time2str($current, 'Y')) return time2str($timestamp, 'm-d H:i');
	return time2str($timestamp);
}

function str2time($str) {
	$timestamp = strtotime($str);
	//if ($timezone = Wekit::C('site', 'time.timezone')) $timestamp -= $timezone * 3600;
	return $timestamp;
}

function time2str($timestamp, $format = 'Y-m-d H:i') {
	if (!$timestamp) return '';
	return date($format, $timestamp);
}

//计算今天或明天
function calRecentDay($timestamp) {
	$current = time();
	$decrease = str2time(time2str($current, 'Y-m-d')) - $timestamp;
	if ($decrease > 0 && $decrease < 86400) {
		return '今';
	} else if ($decrease > 86400 && $decrease < 172800) {
		return '明';
	}
}

//防csrf攻击
function getVerify($str) { //一般传入uid即可
	$app = config('SITE_HASH');
	return substr(md5($str . $app . 'UaMMMXAe4zCTI5jPkGRO0lyrg7h6Z8DJFYoLv1pdiW29bQsqKHmVuMtBncx3Sw'), 8, 8);

// 	$onlineip = pwGetIp();
// 	$app = empty($db_pptkey)?$db_siteid:$db_pptkey;
// 	return substr(md5($onlineip . $app . $pwServer['HTTP_USER_AGENT']), 8, 8);
}
// function setVerify($str) {
// 	$csrfValue = randstr(8);
// 	cookie("csrfcookie", $csrfValue);
// 	$verifyhash = getVerify($str);
// 	return $verifyhash;
// }
function checkVerify($requestVerify, $verifyhash) {
	if ($requestVerify == $verifyhash) {
		//echo 1;exit;
		return true;
	}
	return false;
}
//防csrf攻击 end

function GetCookie($cookieName) {
	return $_COOKIE[cookiePre() . '_' . $cookieName];
}
function cookiePre() {
	return config('SITE_COOKIEPRE');
}
function StrCode($string, $action = 'ENCODE') {
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	/* xintiao 兼容蛋疼的360浏览器
	$key = substr(md5($GLOBALS['pwServer']['HTTP_USER_AGENT'] . $GLOBALS['db_hash']), 8, 18); */
	/*$key = strpos($GLOBALS['pwServer']['HTTP_USER_AGENT'],'360SE') !== FALSE ? substr(md5('UaNfEXAe4zCTI5jPkGRO0lyrg7h6Z8DJFYoLv1pdiW29bQsqKHmVuMtBncx3Sw' . $GLOBALS['db_hash']), 8, 18) : substr(md5($GLOBALS['pwServer']['HTTP_USER_AGENT'] . $GLOBALS['db_hash']), 8, 18);*/
	$key = substr(md5('UaNfEXAe4zCTI5jPkGRO0lyrg7h6Z8DJFYoLv1pdiW29bQsqKHmVuMtBncx3Sw' . config('SITE_HASH')), 8, 18);
	$keyLen = strlen($key);
	$strLen = strlen($string);
	for ($i = 0; $i < $strLen; $i++) {
		$k = $i % $keyLen;
		$code .= $string[$i] ^ $key[$k];
	}
	return ($action != 'DECODE' ? base64_encode($code) : $code);
}

/**
 * 变量导出为字符串
 *
 * @param mixed $input 变量
 * @param string $indent 缩进
 * @return string
 */
function pw_var_export($input, $indent = '') {
	switch (gettype($input)) {
		case 'string' :
			return "'" . str_replace(array("\\", "'"), array("\\\\", "\'"), $input) . "'";
		case 'array' :
			$output = "array(\r\n";
			foreach ($input as $key => $value) {
				$output .= $indent . "\t" . pw_var_export($key, $indent . "\t") . ' => ' . pw_var_export($value, $indent . "\t");
				$output .= ",\r\n";
			}
			$output .= $indent . ')';
			return $output;
		case 'boolean' :
			return $input ? 'true' : 'false';
		case 'NULL' :
			return 'NULL';
		case 'integer' :
		case 'double' :
		case 'float' :
			return "'" . (string) $input . "'";
	}
	return 'NULL';
}

function curlGetOrigin($url){
    $ch = curl_init($url);
    //Header部分的Content-type要设置
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

function curlGet($url){
	//echo $url;
    $ch = curl_init($url);
    //Header部分的Content-type要设置
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json; charset=utf-8"));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    //print_r($output);exit;
    $result = json_decode($output, true);
    return $result;
}

function curlPost($url, $data, $isOrigin = 0) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    //curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array("Expect:"));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    $output = curl_exec($ch);
    curl_close($ch);
    //echo 'output:';print_r($output);
    if ($isOrigin) {
    	return $output;
    } else {
    	$result = json_decode($output, true);
    	return $result;
    }
}

function showDbError($db) {
	$str = "  lastsql：".$db->getLastSql();
	//$str = "  错误sql：".$Db->getLastSql().' error：'.$Db->getDbError();
	return $str;
}

function postMultiParam() {
	//多选的情况
	$ids = input('param.ids/a', '', '', 'pwEscape');

	//单选的情况
	$id = input('param.id', '', '', 'intval');
	if ($id) {
		$ids = [$id];
		unset($id);
	}

	if (!is_array($ids)) {
		return array(0, "请选择信息");
	}

	if (count($ids) <= 0) {
		return array(0, "请选择信息");
	}
	//print_r($ids);

	return array(1, "", ['ids'=>$ids]);
}

/**
 * 优酷视频上传
 * 装配好的html：<iframe height=498 width=510 src="http://player.youku.com/embed/XMzg0MTE4NzAyMA==" frameborder=0 allowfullscreen></iframe>
 * 原始链接：http://player.youku.com/player.php/sid/XMzg0MTE4NzAyMA==/isShowRelatedVideo/false/v.swf
 */
function parseYouku($url, $vid = '') {
	//echo $vid;exit;
	//解析视频上传
	if ($vid) {

	} else {
		if (strpos($url, 'partnerid')) {
			$url = preg_replace("/\\/partnerid\/(.*)\/v.swf/is","", $url);
			$vid = str_replace(array('http://player.youku.com/player.php/sid/'), array(''), $url);
		} else {
			$vid = str_replace(array('http://player.youku.com/player.php/sid/', '/v.swf'), array('', ''), $url);
		}
	}

	$newUrl = "http://player.youku.com/embed/".$vid;
	//echo $url.'<br>'.$newUrl;exit;
	$width = '100%';
	$height = '300';
	$html = '<iframe height='.$height.' width='.$width.' src="'.$newUrl.'" frameborder=0 allowfullscreen></iframe>';

	return $html;
}

/*移动端判断*/
function isMobile()
{
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    {
        // 找不到为flase,否则为true
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    // 脑残法，判断手机发送的客户端标志,兼容性有待提高
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
            );
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
    return false;
}

/**
 * 操作加锁
 *
 * @param string $action 操作名
 * @param int $uid
 * @return bool 是否成功
 */
function procLock($action, $uid = 0) {
	$proclockDao = db('proclock');
	$nowTime = time();
	$map = array();
	$map['uid'] = $uid;
	$map['action'] = $action;
	$checkInfo = $proclockDao->where($map)->find();
	if ($checkInfo) {
		$map = array();
		$map['uid'] = $uid;
		$map['action'] = $action;
		$map['time'] = array('lt', $nowTime - 30);
		$proclockDao->where($map)->delete();
		return false;
	} else {
		$data = array();
		$data['uid'] = $uid;
		$data['action'] = $action;
		$data['time'] = $nowTime;
		$result = $proclockDao->insert($data);
		return true;
	}
}

/**
 * 操作解锁
 *
 * @param string $action 操作名
 * @param int $uid
 */
function procUnLock($action = '', $uid = 0) {
	$proclockDao = db('proclock');
	$map = array();
	$map['uid'] = $uid;
	$map['action'] = $action;
	$proclockDao->where($map)->delete();
}

/**
 * 二维数组排序
 */
function vieworderSort($a, $b) {
    //echo 1;exit;
    //print_r($a);exit;
    return ($a['vieworder'] < $b['vieworder']) ? 1 : -1;
}
/**
 * 计算运费
 */
function calculationDelivery($weight, $first_amount, $first_fee, $additional_amount, $additional_fee) {
	if ($weight > $first_amount) {
		$tmpWeight = $weight - $first_amount;
		$tmpPrice = $first_fee + $additional_fee;
		while ($tmpWeight >= $additional_amount) {
			$tmpWeight = $tmpWeight - $additional_amount;
			$tmpPrice += $additional_fee;
		}
	} else {
		$tmpPrice = $first_fee;
	}
	//print_r($tmpPrice);exit;

	return $tmpPrice;
}
/**
 * 处理链接
 */
function dealLink($page_flag, $page_data='') {
	if ($page_flag == 'index') {
		$link = url('mobmall/index/index');
	} else if ($page_flag == 'product_detail') {
		$link = url('mobmall/product/index', ['pid'=>$page_data]);
	} else if ($page_flag == 'category') {
		$link = url('mobmall/category/index', ['cid'=>$page_data]);
	} else if ($page_flag == 'mine') {
		$link = url('mobmall/mine/index');
	} else if ($page_flag == 'shoppingcart') {
		$link = url('mobmall/shoppingcart/index');
	} else if ($page_flag == 'shop') {
		$link = url('mobmall/shop/index');
	} else if ($page_flag == 'article_detail') {
		$link = url('mobmall/article/detail', ['id'=>$page_data]);
	} else if ($page_flag == 'list') {
		if ($page_data == 'product_list') {

		} else if ($page_data == 'active') {

		} else if ($page_data == 'shop') {
			$link = url('mobmall/shop/index');
		} else if ($page_data == 'evaluation') {
			$link = url('mobmall/evaluation/index');
		} else {
			$link = url('mobmall/index/index');
		}
	} else {
		$link = url('mobmall/index/index');
	}
	return $link;
}
function sendTemplateMessage($list, $tmplmsgRuleInfo, $nowTime='') {
	!$nowTime && $nowTime = time();
	//print_r($list);exit;
/*
Array ( [touser] => omLEn0smHenE1geAoUwYOpj7ZNM4 [template_id] => AIRytMvCGZlZcxKORBzWej6zx-Uu3gmIydY8Y7tZXU8 [url] => [topcolor] => #FF0000 [data] => Array ( [first] => Array ( [value] => 订单发货通知 [color] => #173177 ) [keyword1] => Array ( [value] => 121022504550670000088 [color] => #173177 ) [keyword2] => Array ( [value] => 2021-02-25 22:52 [color] => #173177 ) [keyword3] => Array ( [value] => [color] => #173177 ) [keyword4] => Array ( [value] => [color] => #173177 ) [remark] => Array ( [value] => [color] => #173177 ) ) )
*/
	//获取微信公众号账号
	$weixinAccountDao = model('weixin_manage/WeixinAccount');
	$weixinAccountInfo = $weixinAccountDao->getInfo(config('authorize_wid'));

	//微信jssdk
	$jssdk = new \org\weixin\jssdk($weixinAccountInfo['appid'], $weixinAccountInfo['appsecret'], $weixinAccountInfo['wxnumber']);
	$signPackage = $jssdk->getSignPackage();

	//获取缓存中的access_token
	$access_token = $jssdk->getAccessTokenForOut();

	$options = array(
		'token'=>$weixinAccountInfo['token'], //填写你设定的key
		'encodingaeskey'=>$weixinAccountInfo['aeskey'], //填写加密用的EncodingAESKey
		'appid'=>$weixinAccountInfo['appid'], //填写高级调用功能的app id, 请在微信开发模式后台查询
		'appsecret'=>$weixinAccountInfo['appsecret'], //填写高级调用功能的密钥
		'partnerid'=>'', //财付通商户身份标识，支付权限专用，没有可不填
		'partnerkey'=>'', //财付通商户权限密钥Key，支付权限专用
		'paysignkey'=>'' //商户签名密钥Key，支付权限专用
	);
	$weObj = new \wechat\Wechat($options);

	//使用jssdk获取到的access_token赋值，下文要用
	$weObj->checkAuth('', '', $access_token);

	foreach ($list as $key => $value) {
		if ($value['openid']) {
			$newData = [
				'touser' 		=> $value['openid'],
				'template_id' 	=> $value['template_id'],
				'url' 			=> $value['url'],
				'topcolor' 		=> $value['topcolor'],
				'data'		 	=> $value['data'],
			];
			//print_r($newData);
			$result = $weObj->sendTemplateMessage($newData);
			//echo 'result:';print_r($result);exit;
			if ($result !== false) {
				db('TmplmsgLog')->insert(['alias'=>$tmplmsgRuleInfo['alias'], 'flag'=>'1', 'uid'=>$value['id'], 'username'=>$value['username'], 'openid'=>$value['openid'], 'content'=>'', 'extra'=>pw_var_export($value), 'create_time'=>$nowTime]);
			} else {
				db('TmplmsgLog')->insert(['alias'=>$tmplmsgRuleInfo['alias'], 'flag'=>'2', 'uid'=>$value['id'], 'username'=>$value['username'], 'openid'=>$value['openid'], 'content'=>'错误代码：'.$weObj->errCode.'；错误提示：'.$weObj->errMsg, 'create_time'=>$nowTime]);
			}
		} else {
			db('TmplmsgLog')->insert(['alias'=>$tmplmsgRuleInfo['alias'], 'flag'=>'2', 'uid'=>$value['id'], 'username'=>$value['username'], 'openid'=>$value['openid'], 'content'=>'用户openid不存在', 'create_time'=>$nowTime]);
		}
	}
}

/**
 * 计算购物车单个商品邮费
 */
function calculateProductDelivery($cartInfo, $productExtendInfo, $deliveryList, $deliveryRegionGroup, $consigneeInfo) {
	if (!$consigneeInfo) {
		//return array(0, '非法收货地址');
	}

	//计算商品总价
	$productFee = $cartInfo['one_price'] * $cartInfo['buy_num'];

	//初始化
	$productDelivery = 0;

	//计算商品运费,单商品包邮最低价格
	if ($productExtendInfo['reduction_price'] != '0.00' && $productFee > $productExtendInfo['reduction_price']) {
		$deliveryFee = 0;
	} else {
		if ($productExtendInfo['delivery'] == 1) { //运费模板
			if (!$cartInfo['buy_num']) {
				return array(0, '商品购买数量非法');
			}
			$deliveryInfo = $deliveryList[$productExtendInfo['delivery_template']];
			$deliveryRegionList = $deliveryRegionGroup[$productExtendInfo['delivery_template']];
			//echo '运费模板';print_r($deliveryInfo);exit;
			//echo '运费模板物流地区';print_r($deliveryRegionList);exit;
			if ($deliveryInfo['valuation_type'] == 1) { //重量
				if (!$cartInfo['weight']) {
					return array(0, '请设置商品重量');
				}
				//先获取商品重量
				$productWeight = $cartInfo['weight'] * $cartInfo['buy_num'];
				//echo '商品重量：'.$productWeight;

				//循环地区以获得我的地区对应运费模板
				foreach ($deliveryRegionList as $key => $value) {
					if (strpos($value['provinces_txt'], $consigneeInfo['province']) !== false) {
						$productDelivery = calculationDelivery($productWeight, $value['first_amount'], $value['first_fee'], $value['additional_amount'], $value['additional_fee']);
					}
				}
				//echo '重量商品运费：'.$productDelivery;exit;
			} else if ($deliveryInfo['valuation_type'] == 2) { //件数
				//先获取商品件数
				$productNum = $cartInfo['buy_num'];
				//print_r($productNum);exit;

				//循环地区以获得我的地区对应运费模板
				foreach ($deliveryRegionList as $key => $value) {
					if (strpos($value['provinces_txt'], $consigneeInfo['province']) !== false) {
						$productDelivery = calculationDelivery($productNum, $value['first_amount'], $value['first_fee'], $value['additional_amount'], $value['additional_fee']);
					}
				}
				//echo '件数商品运费：'.$productDelivery;exit;
			}
		}
	}
	return array(1, '', $productDelivery);
}

function getPagePath($page_flag, $page_data) {
	$pagePath = '/pages/index/index';
	$pageJump = 0;
	if ($page_flag == 'index') {
		$pagePath = '/pages/index/index';
		$pageJump = 1;
	} else if ($page_flag == 'classify') {
		$pagePath = '/pages/classify/classify';
		$pageJump = 1;
	} else if ($page_flag == 'mine') {
		$pagePath = '/pages/user/mine';
		$pageJump = 1;
	} else if ($page_flag == 'shopcart') {
		$pagePath = '/pages/shopcart/shopcart';
		$pageJump = 1;
	} else if ($page_flag == 'enter') {
		$pagePath = '/pages/shop/enter';
	} else if ($page_flag == 'product_list') {
		$pagePath = '/pages/product/productList?cid='.$page_data;
	} else if ($page_flag == 'product_detail') {
		$pagePath = '/pages/product/productDetail?pid='.$page_data;
	} else if ($page_flag == 'shop_list') {
		$pagePath = '/pages/shop/shopList?cid='.$page_data;
	} else if ($page_flag == 'shop_detail') {
		$pagePath = '/pages/shop/shopDetail?shid='.$page_data;
	} else if ($page_flag == 'article_list') {
		$pagePath = '/pages/article/articleList?cid='.$page_data;
	} else if ($page_flag == 'article_detail') {
		$pagePath = '/pages/article/articleDetail?arid='.$page_data;
	} else if ($page_flag == 'market_list') {
		$pagePath = '/pages/market/marketList?cid='.$page_data;
	} else if ($page_flag == 'market_detail') {
		$pagePath = '/pages/market/marketDetail?maid='.$page_data;
	} else if ($page_flag == 'forum_index') {
		$pagePath = '/pages/forum/forum';
	}
	return array($pagePath, $pageJump);
}

//BD-09(百度)坐标转换成GCJ-02(火星，高德)坐标
//@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_decrypt($bd_lon,$bd_lat){
	$x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	$x = $bd_lon - 0.0065;
	$y = $bd_lat - 0.006;
	$z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
	$theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
	// $data['gg_lon'] = $z * cos($theta);
	// $data['gg_lat'] = $z * sin($theta);
	$gg_lon = $z * cos($theta);
	$gg_lat = $z * sin($theta);
	// 保留小数点后六位
	$gg_lon = round($gg_lon, 6);
	$gg_lat = round($gg_lat, 6);
	return array($gg_lon, $gg_lat);
}

//过滤掉emoji表情
function filterEmoji($str) {
	$str = preg_replace_callback( '/./u',
		function (array $match) {
			return strlen($match[0]) >= 4 ? '' : $match[0];
		},
	$str);
	return $str;
}

/**
 * 获取微妙时间
 *
 * performance 2010-2-10
 * @return float
 */
function pwMicrotime() {
	$t_array = explode(' ', microtime());
	return $t_array[0] + $t_array[1];
}
function parseUserGroups($limit_group, $userGroupList) {
	if ($limit_group) {
		$groups = explode(",", $limit_group);
		$groupNameArr = array();
		foreach ($groups as $key => $value) {
			$groupNameArr[] = $userGroupList[$value]['name'];
		}
		return implode(",", $groupNameArr);
	} else {
		return '';
	}
}
function buildOrderNo($type, $uid) {
	//生成24位唯一订单号码，格式：YYYY-MMDD-HHII-SS-NNNN,NNNN-CC，其中：YYYY=年份，MM=月份，DD=日期，HH=24格式小时，II=分，SS=秒，NNNNNNNN=随机数，CC=检查码
	$order_date = date('Ymd');
	//订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
	$order_id_main = $order_date.rand(10,99);
	//echo '<br>'.$order_id_main;
	//订单号码主体长度
	$order_id_len = strlen($order_id_main);
	$order_id_sum = 0;
	for($i=0; $i<$order_id_len; $i++){
		$order_id_sum += (int)(substr($order_id_main,$i,1));
	}
	//唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
	$order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100,2,'0',STR_PAD_LEFT);
	//echo '<br>'.$order_id;exit;
	$orderId = str_pad($type, 2, '0', STR_PAD_RIGHT).$order_id.str_pad($uid, 6, "0", STR_PAD_LEFT);
	//echo '<br>'.$orderId;exit;
	//10202106091178000010
	return $orderId;
}